package com.jianzh5.service.impl;

import com.google.common.collect.Lists;
import com.jianzh5.common.DataPage;
import com.jianzh5.common.DataTables;
import com.jianzh5.dao.BaseDaoI;
import com.jianzh5.entity.TCategory;
import com.jianzh5.pojo.PCategory;
import com.jianzh5.service.CategoryServiceI;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Service("categoryService")
public class CategoryServiceImpl implements CategoryServiceI {
	@Autowired
	private BaseDaoI<TCategory> categoryDao;

	public DataTables dataTables(String order, String sort, DataPage datapage) {
		String hql = "from TCategory t";
		String totalHql = "select count(*) "+hql;
		hql += " order by t."+sort+" "+ order;
		List<TCategory> tlist = categoryDao.findByPosition(hql,datapage.getStart(), datapage.getLength());
		List<PCategory> plist = Lists.newArrayList();
		for(TCategory t : tlist){
			PCategory p = new PCategory();
			BeanUtils.copyProperties(t, p);
			plist.add(p);
		}
		long records = categoryDao.count(totalHql);
		DataTables dt = new DataTables();
		dt.setDraw(datapage.getDraw());
		dt.setRecordsTotal(records);
		dt.setRecordsFiltered(records);
		dt.setData(plist);
		return dt;
	}

	public void addCategory(PCategory pcate) {
		TCategory t = new TCategory();
		BeanUtils.copyProperties(pcate, t);
		categoryDao.save(t);
	}

	public void delCategory(int id) {
		TCategory t = categoryDao.get(TCategory.class, id);
		categoryDao.delete(t);
	}

	public PCategory getPCategory(int id) {
		PCategory p = new PCategory();
		TCategory t = categoryDao.get(TCategory.class, id);
		BeanUtils.copyProperties(t, p);
		return p;
	}

	public void editCategory(PCategory pcate) {
		TCategory t = new TCategory();
		BeanUtils.copyProperties(pcate, t);
		categoryDao.update(t);
	}

	public List<PCategory> cateList() {
		String hql = "from TCategory t order by t.seq asc";
		List<TCategory> tlist = categoryDao.find(hql);
		List<PCategory> plist = Lists.newArrayList();
		for(TCategory t : tlist){
			PCategory p = new PCategory();
			BeanUtils.copyProperties(t, p);
			plist.add(p);
		}
		return plist;
	}
	
}
